package org.voovan.korla.rpc.message;

import org.voovan.korla.message.Msg;
import org.voovan.tools.serialize.TSerialize;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 *  Rpc 请求对象
 *
 * @author: helyho
 * korla Framework.
 * WebSite: https://github.com/helyho/korla
 * Licence: Apache v2 License
 */
public class RpcCall extends Msg {
    private String node;
    private String rpcMethodName;
    private List<byte[]> params = new ArrayList<byte[]>();
    private transient int retryCount = 0;

    public RpcCall() {
    }

    public RpcCall(String rpcMethodName) {
        this.rpcMethodName = rpcMethodName;
    }

    private RpcCall(String rpcMethodName, Object ... params) {
        this.rpcMethodName = rpcMethodName;
        this.addParams(params);
    }

    public RpcCall(Long id, String rpcMethodName) {
        super(id);
        this.rpcMethodName = rpcMethodName;
    }

    public String getNode() {
        return node;
    }

    public void setNode(String node) {
        this.node = node;
    }

    public String getRpcMethodName() {
        return rpcMethodName;
    }

    public List getParams() {
        return params;
    }

    public Object[] getParamArray() {
       if(params==null) {
           return null;
       }  else {
           Object[] paramObjs = new Object[params.size()];
            for(int i=0;i<params.size();i++) {
                paramObjs[i] = TSerialize.unserialize(params.get(i));
                if(paramObjs[i].equals(RpcNull.RPC_NULL_ARGS)) {
                    paramObjs[i] = null;
                }
            }

            return paramObjs;
       }
    }

    public void addParam(Object param) {
        params.add(TSerialize.serialize(param == null ? RpcNull.RPC_NULL_ARGS : param));
    }

    public void addParams(Object[] params) {
        for(Object param : params) {
            addParam(param);
        }
    }

    public int getRetryCount() {
        return retryCount;
    }

    public int incrementRetryCount() {
        this.retryCount = retryCount + 1;
        return this.retryCount;
    }

    public void setRetryCount(int retryCount) {
        this.retryCount = retryCount;
    }

    public static RpcCall newInstance(String rpcMethodName, Object ... params) {
        return new RpcCall(rpcMethodName, params);
    }
}
